# redis mysql
import pymysql
import redis


class DataSync:
    def __init__(self):
        try:
            self.conn = pymysql.Connect(
                host='192.168.88.88',
                port=3306,
                user='root',
                password='123456',
                db='tedu_test',
                charset='utf8'
            )
            self.cur = self.conn.cursor()
        except Exception as e:
            print('mysql Error:', e)
            exit(1)
        try:
            self.r = redis.Redis(
                host='192.168.88.88',
                port=6379,
                db=0
            )
        except Exception as e:
            print('redis Error: ', e)
            exit(1)

    def get_data(self, id):
        redis_name = f'student_{id}'
        redis_result = self.r.hgetall(redis_name)
        print(redis_result)
        if len(redis_result) > 0:
            self.r.expire(redis_name, 600)
            return redis_result

        sql = 'select * from tedu_tudent where stu_id=%s'
        self.cur.execute(sql, (id,))
        result = self.cur.fetchone()
        print(result)
        stu_dict = {
            'stu_id': result[0],
            'stu_name': result[1],
            'stu_birth': str(result[2]),
            'stu_phone': result[-1]
        }
        print(stu_dict)

        for key, value in stu_dict.items():
            self.r.hset(redis_name, key, value)
        self.r.expire(redis_name, 600)

        return stu_dict

    def delete_data(self, id):
        sql = 'delete from tedu_student where stu_id=%s'
        self.cur.execute(sql, (id, ))
        self.conn.commit()
        redis_name = f'student_{id}'
        self.r.delete(redis_name)


def get_dict(dict01):
    dict02 = {}
    for key, value in dict01.items():
        # print(key, value)
        key = str(key, encoding='utf-8')
        value = str(value, encoding='utf-8')
        dict02[key] = value
    return dict02

if __name__ == '__main__':
    d = DataSync()
    data = d.get_data(1001)
    print(data)
    d.delete_data(1003)
